package com.aishua.aishuawallet.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aishua.aishuawallet.Constant;
import com.aishua.aishuawallet.R;
import com.aishua.aishuawallet.adapter.TransactionAdapter;
import com.aishua.aishuawallet.bean.ReqTransBean;
import com.aishua.aishuawallet.bean.ReqTransnation;
import com.aishua.aishuawallet.diydialog.SublimePickerFragment;
import com.aishua.aishuawallet.utils.AndroidUtils;
import com.aishua.aishuawallet.utils.LogUtils;
import com.aishua.aishuawallet.utils.TimeUtil;
import com.aishua.aishuawallet.utils.TimeUtils;
import com.aishua.aishuawallet.web3jmanager.Web3jManager;
import com.appeaser.sublimepickerlibrary.datepicker.SelectedDate;
import com.appeaser.sublimepickerlibrary.helpers.SublimeOptions;
import com.appeaser.sublimepickerlibrary.recurrencepicker.SublimeRecurrencePicker;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.web3j.utils.Convert;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by aishua on 2018/8/8.
 */

public class RecordActivity extends BaseActivity {

    private static final String TAG = "RecordActivity-";
    private Toolbar toolbar;
    private BarChart bar_chart_record;
    private BarChartManager barChartManager1;
    private RecyclerView rl_latelytra;
    private ImageView img_pickertiem;
    private List<String> timeList;
    private LinearLayout ll_bottom;
    private boolean isdispaly;
    private Button btn_transfer;
    private Button btn_receivables;
    private TextView toolbar_title;
    private String tokenaddr;
    private ReqTransnation reqTransnation;
    private TextView tv_eth;
    private TextView tv_ethtormb;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case 1:
                    reqTransnation = (ReqTransnation) msg.getData().getSerializable("reqTransnation");
                    recycleViewdata();
                    setBarChart();
                    break;
                case 2:

                    double balace1 = (double) msg.obj;

                    tv_eth.setText(String.format("%.1f", Double.valueOf(balace1)));
                    tv_ethtormb.setText("(¥)≈" + String.format("%.1f", Double.valueOf(balace1) * 1900));
                    break;
            }


        }
    };
    //回调函数
    SublimePickerFragment.Callback mFragmentCallback = new SublimePickerFragment.Callback() {
        @Override
        public void onCancelled() {
        }

        @Override
        public void onDateTimeRecurrenceSet(SelectedDate selectedDate, int hourOfDay, int minute,
                                            SublimeRecurrencePicker.RecurrenceOption recurrenceOption, String recurrenceRule) {
            Date date = selectedDate.getFirstDate().getTime();
            timeList.clear();
            getTime(date);

        }
    };

    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record1);
        initToolbar();
        initVIew();
        getData();
        initData();

        isdispalyButton();
        getBalance();

    }


    @Override
    protected void onResume() {
        super.onResume();
        getRecordAsync("0x3907d69517b58355207e9a371add9dbc1e198a5b");

    }

    private void getBalance() {

        new Thread() {
            @Override
            public void run() {

                double balace = getBalace(Constant.ADDRESS_OWN);
                Message message = mHandler.obtainMessage();
                message.what = 2;
                message.obj = balace;
                mHandler.sendMessage(message);
            }
        }.start();
    }

    private void initToolbar() {

        toolbar = findViewById(R.id.toolbar);
        toolbar_title = findViewById(R.id.toolbar_title);
        toolbar_title.setText("ETH");
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });

    }

    private void initData() {

        Date date = Calendar.getInstance().getTime();
        timeList = new ArrayList<>();
        timeList.clear();
        getTime(date);

    }


    private void initVIew() {

        tv_eth = findViewById(R.id.tv_eth);
        tv_ethtormb = findViewById(R.id.tv_ethtormb);
        bar_chart_record = findViewById(R.id.bar_chart_record);
        rl_latelytra = findViewById(R.id.rl_latelytra);
        ll_bottom = findViewById(R.id.ll_bottom);
        barChartManager1 = new BarChartManager(this, bar_chart_record);
        bar_chart_record.setDrawGridBackground(false);
        img_pickertiem = findViewById(R.id.img_pickertiem);
        btn_transfer = findViewById(R.id.btn_transfer);
        btn_receivables = findViewById(R.id.btn_receivables);
        img_pickertiem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SublimePickerFragment pickerFrag = new SublimePickerFragment();
                pickerFrag.setCallback(mFragmentCallback);

                //将信息传入到options中。
                SublimeOptions options = new SublimeOptions();
                int displayOptions = 0;
                displayOptions |= SublimeOptions.ACTIVATE_DATE_PICKER;
                options.setPickerToShow(SublimeOptions.Picker.DATE_PICKER);
                options.setDisplayOptions(displayOptions);
                options.setCanPickDateRange(true);

                // Valid options
                Bundle bundle = new Bundle();
                bundle.putParcelable("SUBLIME_OPTIONS", options);
                pickerFrag.setArguments(bundle);

                pickerFrag.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
//                pickerFrag.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
                pickerFrag.show(getSupportFragmentManager(), "SUBLIME_PICKER");

            }
        });
        btn_transfer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(RecordActivity.this, TransferActivity.class);


                startActivity(intent);
            }
        });
        btn_receivables.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(RecordActivity.this, ReceivablesActivity.class);
                intent.putExtra("tokenaddr", tokenaddr);
                startActivity(intent);
            }
        });
    }

    private void setBarChart() {
        //设置X轴数据
        ArrayList<Float> xValues = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            xValues.add((float) i);
        }

        List<List<Float>> yValues = getBarcharYvalue();
        List<Float> yValuesout  = new ArrayList<>();
        List<Float> yValuesin = new ArrayList<>();
        yValuesout.addAll(yValues.get(0));
        yValuesin.addAll(yValues.get(1));
        yValuesout.addAll(yValuesin);
        Float max = Collections.max(yValuesout);
        LogUtils.v(TAG +"yValuesout:"+yValuesout +"max:"+max);
        LogUtils.v(TAG +"yValues:"+yValues);


        //颜色集合
        List<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.deepblue));
        colors.add(getResources().getColor(R.color.lightblue));


        //线的名字集合
        List<String> names = new ArrayList<>();
        names.add(getResources().getString(R.string.transferin));
        names.add(getResources().getString(R.string.transferout));


        //X轴显示字符串------->>

        XAxis xAxis = bar_chart_record.getXAxis();
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {

                return timeList.get((int) value); //mList为存有月份的集合

            }
        });
        //X轴显示字符串-------<<
        barChartManager1.setDescription("");
//        动态设置最大，显示最大的80%
        barChartManager1.setYAxis(max * 1.2f, 0, 6);
        barChartManager1.showBarChart(xValues, yValues, names, colors);

    }

    private List<List<Float>> getBarcharYvalue() {

        //设置Y轴数据
        float valueout1 = 0;
        float valuein1 = 0;
        float valueout2 = 0;
        float valuein2 = 0;
        float valueout3 = 0;
        float valuein3 = 0;
        float valueout4 = 0;
        float valuein4 = 0;
        float valueout5 = 0;
        float valuein5 = 0;
        if (null != reqTransnation && reqTransnation.getResult().size() > 0) {

            List<List<Float>> yValues = new ArrayList<>();
            List<Float> yValuein = new ArrayList<>();
            List<Float> yValueout = new ArrayList<>();
            //求出来是12点的，相差12个小时,不知道原因
            long daytimestart = TimeUtils.initDateByDay().getTime() - 43200 * 1000;

            LogUtils.v(TAG + "daytimestart:" + daytimestart);
            List<ReqTransnation.TransntionResult> transntionResults = reqTransnation.getResult();

            for (int i = 0; i < transntionResults.size(); i++) {

                long recordtime = Long.valueOf(transntionResults.get(i).getTimeStamp() + "000");
                LogUtils.v(TAG + "recordtime:" + recordtime);
                String from = reqTransnation.getResult().get(i).getFrom();
                long dalue = daytimestart - recordtime;
                LogUtils.v(TAG + "DALUE:" + dalue);

                // 小于24*60*60*1000 毫秒 表示在同一天
                if (dalue < 0) {

                    if ("0x3907d69517b58355207e9a371add9dbc1e198a5b".equals(from)) {
//             表示转出
                        valueout1 = valueout1 + Float.valueOf(Convert.fromWei(transntionResults.get(i).getValue(), Convert.Unit.ETHER).toString());
                    } else {
                        valuein1 = valuein1 + Float.valueOf(Convert.fromWei(transntionResults.get(i).getValue(), Convert.Unit.ETHER).toString());
                    }
                } else if (dalue < 1 * 24 * 60 * 60 * 1000) {
                    if ("0x3907d69517b58355207e9a371add9dbc1e198a5b".equals(from)) {
//                            表示转出
                        valueout2 = valueout2 + Float.valueOf(Convert.fromWei(transntionResults.get(i).getValue(), Convert.Unit.ETHER).toString());
                    } else {

                        valuein2 = valuein2 + Float.valueOf(Convert.fromWei(transntionResults.get(i).getValue(), Convert.Unit.ETHER).toString());
                    }
                } else if (dalue < 2 * 24 * 60 * 60 * 1000) {
                    if ("0x3907d69517b58355207e9a371add9dbc1e198a5b".equals(from)) {
//                            表示转出
                        valueout3 = valueout3 + Float.valueOf(Convert.fromWei(transntionResults.get(i).getValue(), Convert.Unit.ETHER).toString());

                    } else {

                        valuein3 = valuein3 + Float.valueOf(Convert.fromWei(transntionResults.get(i).getValue(), Convert.Unit.ETHER).toString());
                    }
                } else if (dalue < 3 * 24 * 60 * 60 * 1000) {
                    if ("0x3907d69517b58355207e9a371add9dbc1e198a5b".equals(from)) {
//                            表示转出
                        valueout4 = valueout4 + Float.valueOf(Convert.fromWei(transntionResults.get(i).getValue(), Convert.Unit.ETHER).toString());

                    } else {

                        valuein4 = valuein4 + Float.valueOf(Convert.fromWei(transntionResults.get(i).getValue(), Convert.Unit.ETHER).toString());
                    }
                } else if (dalue < 4 * 24 * 60 * 60 * 1000) {
                    if ("0x3907d69517b58355207e9a371add9dbc1e198a5b".equals(from)) {
//                            表示转出
                        valueout5 = valueout5 + Float.valueOf(Convert.fromWei(transntionResults.get(i).getValue(), Convert.Unit.ETHER).toString());

                    } else {

                        valuein5 = valuein5 + Float.valueOf(Convert.fromWei(transntionResults.get(i).getValue(), Convert.Unit.ETHER).toString());
                    }

                } else {

                    break;
                }
            }
            yValuein.add(valuein5);
            yValueout.add(valueout5);
            yValuein.add(valuein4);
            yValueout.add(valueout4);
            yValuein.add(valuein3);
            yValueout.add(valueout3);
            yValuein.add(valuein2);
            yValueout.add(valueout2);
            yValuein.add(valuein1);
            yValueout.add(valueout1);

            LogUtils.v(TAG + "yValuein:" + yValuein + "--yValueout:" + yValueout);
            yValues.add(yValuein);
            yValues.add(yValueout);
            return yValues;
        }
        return null;
    }

    private void recycleViewdata() {


        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this,
                LinearLayoutManager.VERTICAL, false);
        rl_latelytra.setLayoutManager(layoutManager);
//        rl_account.setItemAnimator(new DefaultItemAnimator());
//        rl_account.addItemDecoration(new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, 2, Color.GRAY));

        rl_latelytra.setAdapter(new TransactionAdapter(this, reqTransnation));

    }


    private void getTime(Date date) {

        String time = TimeUtils.DateToString(date);
        for (int i = 0; i < 5; i++) {

            timeList.add(time);
            date = TimeUtils.getDateBefore(date, 1);
            time = TimeUtils.DateToString(date);
        }
        Collections.reverse(timeList);

    }

    public void isdispalyButton() {

        isdispaly = getIntent().getBooleanExtra(Constant.ISDISPALY, false);
        if (isdispaly) {

            ll_bottom.setVisibility(View.VISIBLE);
        } else {
            ll_bottom.setVisibility(View.GONE);
        }

    }

    public void getData() {

        tokenaddr = getIntent().getStringExtra("tokenaddr");


    }


    private void getRecordAsync(String address) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://api-rinkeby.etherscan.io/api?module=account&action=txlist&address=" + address + "&startblock=0&endblock=99999999&sort=desc&apikey=YourApiKeyToken")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                if (response.isSuccessful()) {

                    //回调的方法执行在子线程。Log.d("kwwl","获取数据成功了");
                    Log.d("kwwl", "response.code()==" + response.code());
                    String result = response.body().string();

                    Gson gson2 = new GsonBuilder().disableHtmlEscaping().create();
                    ReqTransnation reqTransnation = gson2.fromJson(result, ReqTransnation.class);
                    LogUtils.v(TAG + "reqTransBean:" + reqTransnation);
                    Message message = Message.obtain();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("reqTransnation", reqTransnation);
                    message.setData(bundle);
                    message.what = 1;
                    mHandler.sendMessage(message);

                }
            }
        });
    }

    public double getBalace(String address) {

        double balace = 0;
        Web3jManager web3jManager = Web3jManager.getIntance();
        try {

            balace = web3jManager.getBalance(address);


        } catch (ExecutionException e) {

            e.printStackTrace();
        } catch (InterruptedException e) {

            e.printStackTrace();
        }
        return balace;

    }


}
